<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <el-col :span="18" style="height:400px;">
        <el-button plain @click="realtimeSetting.scale=1;getList()">1M</el-button>
        <el-button plain @click="realtimeSetting.scale=60;getList()">1H</el-button>
        <el-button plain @click="realtimeSetting.scale=1440;getList()">日线</el-button>
        <el-button style="float: right; padding: 3px 0" type="text" @click="getList">刷新</el-button>
        <div id="chart" style="height:400px;"></div>
      </el-col>
      <el-col :span="6" style="height:400px;">
        <el-card shadow="always">
          <div slot="header" class="clearfix">
            <span>信号</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="getPolicyList">更多</el-button>
          </div>
         <el-table
          :data="policyList"
          stripe
          height="400"
          style="width: 100%">
          <el-table-column
            prop="cycle"
            label="时间"
            width="115">
          </el-table-column>
          <el-table-column
            prop="direction"
            label="趋势">
            <template slot-scope="{row}">
              <el-tag v-if="row.direction == 1">看多</el-tag><el-tag v-else>看空</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="lDirection"
            label="长期趋势">
            <template slot-scope="{row}">
              <el-tag v-if="row.lDirection == 1">看多</el-tag><el-tag v-else>看空</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="signal"
            width="200"
            label="摆动">
            <template slot-scope="{row}">
              <el-tag v-if="row.signal > 80">摸顶</el-tag>
              
              <el-tag v-if="row.signal < 20">挖坑</el-tag>
              <span>{{row.signal}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createdAt"
            width="180"
            label="最后更新">
          </el-table-column>
        </el-table>
         </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-card shadow="always">
          <div slot="header" class="clearfix">
            <span>持仓</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="getPositionList">更多</el-button>
          </div>
         <el-table
          :data="inventoryList"
          stripe
          height="400"
          style="width: 100%">
           <el-table-column
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            label="合约"
            width="180">
            <template slot-scope="{row}">
              <el-tag v-if="row.style == 1">看多</el-tag><el-tag v-else>看空</el-tag>
              <span>{{ row.symbol }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="数量"
            width="180">
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格">
          </el-table-column>
          <el-table-column label="止盈价" min-width="150px">
            <template slot-scope="{row}">
              <span>{{ row.stopProfitPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="profit"
            label="利润">
          </el-table-column>
          <el-table-column
            prop="createdAt"
            width="180"
            label="最后更新">
          </el-table-column>
        </el-table>
         </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="always">
          <div slot="header" class="clearfix">
            <span>委托</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="getAuthorizeList">更多</el-button>
            <el-button style="float: right; padding: 3px 0" type="text" @click="openAuthorizeDialog">开仓</el-button>
          </div>
         <el-table
          :data="authorizeList"
          stripe
          style="width: 100%"
          height="400">
           <el-table-column
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            prop="symbol"
            label="合约"
            width="180">
            <template slot-scope="{row}">
              <el-tag v-if="row.status == 1">待提交</el-tag><el-tag v-else>已提交</el-tag>
              <span>{{ row.symbol }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            width="180">
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="数量">
          </el-table-column>
          <el-table-column
            prop="action"
            label="类型">
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态">
            <template slot-scope="{row}">
              <el-tag v-if="row.status == 1">待提交</el-tag><el-tag v-else>已提交</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createdAt"
            width="180"
            label="发生时间">
          </el-table-column>
        </el-table>
         </el-card>
      </el-col>
    </el-row>
    <el-dialog
  title="委托"
  :visible.sync="authorizeDialogHidden"
  width="30%"
  :before-close="closeAuthorzeButton">
  
<el-form ref="form" :model="authorizeForm" label-width="100px">

  <el-form-item label="方向">
    <el-radio-group v-model="authorizeForm.style" size="small">
      <el-radio-button label="1">看多</el-radio-button>
      <el-radio-button label="2">看空</el-radio-button>
    </el-radio-group>
  </el-form-item>

  <el-form-item label="合约">
    <el-input placeholder="合约" v-model="authorizeForm.symbol"></el-input>
  </el-form-item>
  <el-form-item label="价格">
    <el-input placeholder="价格" v-model="authorizeForm.price"></el-input>
  </el-form-item>

  <el-form-item label="数量">
    <el-input placeholder="数量" v-model="authorizeForm.quantity"></el-input>
  </el-form-item>

  <el-form-item label="类型">
    <el-radio-group v-model="authorizeForm.action" size="small">
      <el-radio-button label="close">平仓</el-radio-button>
      <el-radio-button label="buy">开多仓</el-radio-button>
      <el-radio-button label="sell">开空仓</el-radio-button>
    </el-radio-group>
  </el-form-item>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="authorizeDialogHidden = false">取 消</el-button>
    <el-button type="primary" @click="closeAuthorizeSubmit()">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { init,registerIndicator } from 'klinecharts'
import {getHost} from '@/utils/socket' // secondary package based on el-pagination
export default {
  name: 'Dashboard',
  data() {
    return {
      socket:"",
      tableKey: 0,
      list: null,
      kbarChart:null,
      authorizeDialogHidden:false,
      total: '',
      listLoading: false,
      localSymbol:"i2309",
      symbol:"i2309",
      connected:"loading",
      authorizeForm:{},
      filterForm: {
        page: 1,
        size: 10,
        localSymbol: undefined
      },
      realtimeTimer:false,
      authorizeTimer:false,
      purchaseTimer:false,
      policyTimer:false,
      baseUrl:"#/test-dsfsdfs",
      realtimeSetting:{
        scale:1,
        symbol:"i2309"
      },
      inventoryList:[],
      authorizeList:[],
      shipmentsList:[],
      policyList:[],
      turnoverList:[]
    }
  },
  computed: {
  },
  mounted(){
    // 初始化图表
      this.kbarChart = init("chart")
      registerIndicator({
        name:"bambooMA",
        shortName: 'bbMA',
        // 计算参数是2个，一个计算5个周期时间的均值，即'ma1'，另一个计算10个周期时间的均值，即'ma10'
        calcParams: [60, 120],
        figures: [
          // 第一条线'ma5'
          { key: 'ma1', title: 'MA60: ', type: 'line' },
          // 第二条线'ma10'
          { key: 'ma2', title: 'MA120: ', type: 'line' }
        ],
         // 当计算参数改变时，希望提示的和参数一样，即title的值需要改变
        regenerateFigures: (params) => {
          return params.map((p, i) => {
            return { key: `ma${i + 1}`, title: `MA${p}: `, type: 'line' }
          })
        },
        // 计算结果
        calc: (kLineDataList, { calcParams, figures }) => {
          // 注意：返回数据个数需要和kLineDataList的数据个数一致，如果无值，用{}代替即可。
          // 计算参数最好取回调参数calcParams，如果不是，后续计算参数发生变化的时候，这里计算不能及时响应
          const closeSums = []
          let _ema = {}
          const indicalData = kLineDataList.map((kLineData, i) => {
            const ma = {}
            calcParams.forEach((param, j) => {
                if(i < 1){
                  ma[figures[j].key] = kLineData.close
                }else{
                  var k = 2/(param+1)
                  ma[figures[j].key] = kLineData.close*k+_ema[figures[j].key]*(1-k)
                }
            })
            _ema = ma
            // 如果有值的情况下，这里每一项的数据格式应该是 { ma1: xxx, ma2: xxx }
            // 每个key需要和figures中的子项key对应的值一致
            return ma
          })
          return indicalData
        }
      })
       //取消默认指标
      this.kbarChart.createIndicator('bambooMA', false, { id: "candle_pane",calcParams:[30,60,120] });
  },
  created() {
    //this.symbol = this.$route.query && this.$route.query.symbol
    let symbolData = window.localStorage.getItem('localSymbol')
    symbolData = JSON.parse(symbolData)
    try {
      this.localSymbol = symbolData.code
    } catch (error) {
      
    }
    //this.init()
  },
  destroyed:function(){
    clearInterval(this.realtimeTimer)
    clearInterval(this.policyTimer)
    clearInterval(this.authorizeTimer)
    clearInterval(this.purchaseTimer)
    this.close()
  },
  methods:{
    init: function () {
      if(typeof(WebSocket) === "undefined"){
          alert("您的浏览器不支持socket")
      }else{
          // 实例化socket
          this.socket = new WebSocket(getHost())
          // 监听socket连接
          this.socket.onopen = this.open
          // 监听socket连接
          this.socket.onclose = this.close
          // 监听socket错误信息
          this.socket.onerror = this.error
          // 监听socket消息
          this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
        let _this = this;
        this.connected = 'loaded'

        this.getList()
        setTimeout(function(){
            _this.getPolicyList()
        },1000)
        setTimeout(function(){
            _this.getAuthorizeList()
        },2000)
        setTimeout(function(){
            _this.getPositionList()
        },3000)
    },
    error: function (e) {
        console.log("连接错误",JSON.stringify(e))
    },
    getMessage: function (receiveData) {
      let _this = this;
      receiveData = JSON.parse(receiveData.data)
        console.log(receiveData)
      if(receiveData.status != 200){
          console.log(receiveData.msg)
      }else{
        let localUrl = window.location.href
        console.log(localUrl)
        if(receiveData.conversationType == "quotation.realtime.list"){
            _this.kbarChart.applyNewData(receiveData.data.list.reverse())
          if(localUrl.indexOf(_this.baseUrl) >= 0){
            _this.realtimeTimer = setInterval(function(){
              _this.getList()
            },60000)
          }

        }
        if(receiveData.conversationType == "position.authorize.list"){
          _this.authorizeList = receiveData.data.list
          if(localUrl.indexOf(_this.baseUrl) >= 0){
            _this.authorizeTimer = setInterval(function(){
              _this.getAuthorizeList()
            },30000)
          }
        }
        if(receiveData.conversationType == "quotation.policy.list"){
          _this.policyList = receiveData.data.list
          if(localUrl.indexOf(_this.baseUrl) >= 0){
            _this.policyTimer = setInterval(function(){
              _this.getPositionList()
            },6000)
          }
        }
        if(receiveData.conversationType == "position.purchase.list"){
          _this.inventoryList = receiveData.data.list
          if(localUrl.indexOf(_this.baseUrl) >= 0){
            _this.purchaseTimer = setInterval(function(){
              _this.getPositionList()
            },50000)
          }
        }
        if(receiveData.conversationType == "position.authorize.save"){
          _this.authorizeDialogHidden = true
        }
      }
    },
    send: function (params) {
        console.log(this.socket)
      params = JSON.stringify(params)
      try {
        this.socket.send(params)
      } catch (error) {
        console.log("发送失败，socket已经关闭")
      }
    },
    close: function () {
        console.log("socket已经关闭")
        //this.init()
    },
    openAuthorizeDialog:function(){
      this.authorizeDialogHidden = true;

    },
    closeAuthorzeButton:function(){
      this.authorizeDialogHidden = false;
    },
    closeAuthorizeSubmit:function(){
      this.authorizeDialogHidden = false;
      this.send({
        "conversationType":"position.authorize.save",
        "message":this.authorizeForm,
        "target":{"id":"3"}
      })
    },
    getList:function(){
      console.log("读取行情")
      this.send({
        "conversationType":"quotation.realtime.list",
        "message":{"symbol":this.symbol,"scale":this.realtimeSetting.scale,"page":1,"size":1000},
        "target":{"id":"3"}
      })
    },
    getPolicyList:function(){
      console.log("读取委托")
      this.send({
        "conversationType":"quotation.policy.list",
        "message":{"symbol":this.localSymbol,"page":1,"size":20,"scale":this.realtimeSetting.scale},
        "target":{"id":"3"}
      })
    },
    getAuthorizeList:function(){
      console.log("读取委托")
      this.send({
        "conversationType":"position.authorize.list",
        "message":{"symbol":this.symbol,"page":1,"size":20},
        "target":{"id":"3"}
      })
    },
    getPositionList:function(){
      console.log("读取持仓")
      this.send({
        "conversationType":"position.purchase.list",
        "message":{"localSymbol":this.localSymbol,"page":1,"size":20},
        "target":{"id":"3"}
      })
    }
  }
}
</script>
